package com.tiny.work.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer>{
    private static final int THRESHOLD= 2;

    private int start;
    private int end;

    @Override
    protected Integer compute() {
        int sum =0;
        boolean canCompute = (end -start)<=THRESHOLD;
        if (canCompute) {
            for (int i=start;i<=end;i++){
                sum +=i;
            }
        }else {
            int middle = (end+start)/2;
            CountTask leftTask = new CountTask(start, middle);
            CountTask rigthTask = new CountTask(middle+1, end);
            leftTask.fork();
            rigthTask.fork();

            int leftResult = leftTask.join();
            int rightResult = rigthTask.join();
            sum = leftResult +rightResult;
        }
        return sum;
    }

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String args[]) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool =new ForkJoinPool();
        CountTask countTask = new CountTask(1,100000);
        ForkJoinTask<Integer> submit = 
                forkJoinPool.submit(countTask);
        System.out.println(submit.get());
    }
}
